<template>
  <div class="scan">
    <van-nav-bar title="设备巡检" left-arrow="" @click-left='goBack()'></van-nav-bar>
    <van-cell title="区域名称" :value="area"></van-cell>

    <div class="uploadArea">
      <van-field :border="false" v-model="message" rows="3" :clearable="true" autosize type="textarea" placeholder="请输入备注" />
      <!-- <van-uploader :max-count="1" :after-read="onFileChange" v-model="fileList" capture="camera">
        <div slot='default' class="imgslot" ref="divGenres" @click="choiceImg">
          <img class="cremaImg" src="../../assets/imgs/ceram.png" />
          <p class="imgText">拍摄照片</p>
        </div>
      </van-uploader> -->
      <div class="isSub">
        <div class="imgslot" ref="divGenres" v-show="imgSrcArr&&imgSrcArr.length<1" @click="choiceImg">
          <img class="cremaImg" src="../../assets/imgs/ceram.png" />
          <p class="imgText">拍摄照片</p>
          <input multiple="" type="file" name="file" ref="uploadImage" @change="onFileChange" accept="image/*" capture="camera"
            style="display: none;">
        </div>
        <div class="list-li">
          <div style="display: inline-block;">
            <a class="list-link" v-for="(item,i) in imgSrcArr" :key='i'>
              <van-image :src="item" @click='getImgPreview' />
              <img class="delImg" src="../../assets/imgs/delimg.png" @click="delImg(i)" />
            </a>
          </div>
        </div>
      </div>
      <progress :value="progress" max="100" v-show="showp"></progress>
      <div class="btn">
        <van-button type="default" size="large" color="#62cff9" @click='checkok'>完成巡检</van-button>
        <van-button type="default" size="large" @click='goAddFault'>发现故障</van-button>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    Toast
  } from 'vant'
  import {
    ImagePreview
  } from 'vant'
  export default {
    data() {
      return {
        caputerFile: '',
        target: '',
        show: false,
        message: '',
        showCamera: true,
        showp: false,
        progress: '',
        isPhoto: true,
        imgSrcArr: [],
        previewImg: '', //预览图片的地址
        imgsrc: '', //上传的·图片的地址,
        area: '',
        uploadFile: null,
        fileList: [],
        files: []
      }
    },
    created() {
      this.area = this.$route.params.areaName
    },
    methods: {
      afterRead(file) {
        this.uploadFile = file
        console.log(this.uploadFile.file)
        console.log(this.fileList[0].file)
      },
      checkok() {
        if (this.imgSrcArr.length === 0) {
          return Toast.fail({
            message: '您还未上传图片',
            duration: 860
          })
        }
        this.showp = true
        let params = new FormData()
        params.append('img', this.uploadFile)
        params.append('name', this.area)
        params.append('id', this.message)
        let config = {
          header: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            var complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
            console.log(complete) //complete是一个变化的值，最大100上传完成
            this.progress = complete //赋值，进度条变化，通过值或者其他事件还可以用showp使得进度条是否隐藏
            if (this.progress === 100) {
              this.showp = false
            }
          }
        }
        this.$axios.post('UploadFile/uploadFile.do', params, config).then(res => {
          this.showp = false
          if (res.data.status === 200) {
            Toast.success({
              message: '完成巡检',
              duration: 900
            })
          } else if (res.data.status === 202) {
            Toast.fail({
              message: '请上传10M以内的图片',
              duration: 900
            })
          } else if (res.data.status === 201) {
            Toast.fail({
              message: '系统错误',
              duration: 900
            })
          } else if (res.data.status === 204) {
            Toast.fail({
              message: res.data.msg,
              duration: 900
            })
          }
        })
        /* .catch(err => {
                  Toast.fail({
                    message: '上传失败',
                    duration: 900
                  })
                }) */

      },
      //图片预览
      getImgPreview() {
        ImagePreview({
          images: this.imgSrcArr,
          startPosition: 1,
          onClose() {
            // do something
          }
        });
      },
      choiceImg() {
        let self = this;
        if (!window.plus) {
          self.addPic() //如果不支持plus,就用本地相册上传即可
          return;
        }
        let title = "选择照片"
        let btns = ['拍照']

        var func = function(e) {
          var index = e.index;

          if (index == 1) self.choiceCamera();
          if (index == 2) self.choicePic();
        }

        if (title && btns && btns.length > 0) {
          var btnArray = [];
          for (var i = 0; i < btns.length; i++) {
            btnArray.push({
              title: btns[i]
            });
          }

          plus.nativeUI.actionSheet({
            title: title,
            cancel: '取消',
            buttons: btnArray
          }, function(e) {
            if (func) func(e);
          });
        }
      },

      choiceCamera() {
        let self = this;
        var cmr = plus.camera.getCamera();
        cmr.captureImage(function(path) {
          plus.io.resolveLocalFileSystemURL(path, function(entry) {
            self.imgsrc = entry.toLocalURL();
            self.show = true;
            self.imgSrcArr.push(self.imgsrc)

            entry.file(function(file) {
              let reader = null;
              //self.uploadFile = file
              reader = new plus.io.FileReader();
              reader.onload = function(e) {};
              reader.readAsDataURL(file);
              reader.onloadend = function(e) {
                let dataBase = e.target.result;
                self.uploadFile = dataBase
              }
            })
          }, function(e) {
            plus.nativeUI.toast("读取拍照文件错误：" + e.message);
          });
        }, function(e) {
         self.uploadFile = e.files[0]
        }, {
          index: 1,
          filename: "_doc/camera/"
        });
      },

      choicePic() {
        let self = this;
        plus.gallery.pick(function(p) {
          plus.io.resolveLocalFileSystemURL(p, function(entry) {
            self.imgsrc = entry.toLocalURL();
            self.show = true;
            self.imgSrcArr.push(self.imgsrc)
          }, function(e) {
            plus.nativeUI.toast("读取拍照文件错误：" + e.message);
          });
        }, function(e) {
          plus.nativeUI.toast("读取拍照文件错误：" + e.message);
        }, {
          filename: "_doc/camera/",
          filter: "image"
        });
      },
       upload(){
               var self = this
              /* var wt ;
               if (window.plus)
                 wt = plus.nativeUI.showWaiting();
       */
               var img = new Image,
                   width = 512, //image resize   压缩后的宽
                   quality = 0.5, //image quality  压缩质量
                   canvas = document.createElement("canvas"),
                   drawer = canvas.getContext("2d");
              img.src = self.imgsrc;
              img.onload = function(){//利用canvas压缩图片
              canvas.width = width;
              canvas.height = width * (img.height / img.width);
               drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
               var base64 = canvas.toDataURL("image/*", quality);
               var pic = base64.split(',')[1];//图片的base64编码内容
               var f=self.imgsrc;
               var filename=f.replace(f.substring(0, f.lastIndexOf('/') + 1), '');//图片名称

               if(self.uploadFile !== null){//addPic方法得到的图片文件
                 filename =  self.uploadFile.name
                 let reader = new FileReader();
                 reader.readAsDataURL(self.uploadFile);
                 reader.onload = function(e){
                   img.src = e.target.result;
                 }
                img.onload = function(){
                canvas.width = width;
                canvas.height = width * (img.height / img.width);
                 drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
                 base64 = canvas.toDataURL("image/*", quality);
                 setTimeout(()=>{
                   this.showp = true
                   console.log(self.uploadFile)
                   let params = new FormData()
                   params.append('img', base64)
                   params.append('name', self.area)
                   params.append('id', self.message)
                   let config = {
                     header: {
                       'Content-Type': 'multipart/form-data'
                     },
                     onUploadProgress: progressEvent => {
                       var complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
                       console.log(complete) //complete是一个变化的值，最大100上传完成
                       self.progress = complete //赋值，进度条变化，通过值或者其他事件还可以用showp使得进度条是否隐藏
                       if (self.progress === 100) {
                         self.showp = false
                       }
                     }
                   }
                   self.$axios.post('UploadFile/uploadFile.do', params, config).then(res => {
                    // wt.close()
                     self.showp = false
                     if (res.data.status === 200) {
                       Toast.success({
                         message: '完成巡检',
                         duration: 900
                       })
                     } else if (res.data.status === 202) {
                       Toast.fail({
                         message: '请上传10M以内的图片',
                         duration: 900
                       })
                     } else if (res.data.status === 201) {
                       Toast.fail({
                         message: '系统错误',
                         duration: 900
                       })
                     } else if (res.data.status === 204) {
                       Toast.fail({
                         message: res.data.msg,
                         duration: 900
                       })
                     }
                   }).catch(err => {
                     Toast.fail({
                       message: '上传失败',
                       duration: 900
                     })
                   })
                 },500)
               }
               }
      　　　　//此处是将图片上传到服务器的代码，略过
             }
           },

      onFileChange(e) {
        //console.log(this.$refs.uploadImage.files[0])
        let self = this;
        let files = e.target.files || e.dataTransfer.files;
        if (!files.length) return;
        let file = files[0]; //File对象
        self.uploadFile = file;
        let reader = new FileReader(); //FileReader对象
        reader.readAsDataURL(file); //该方法会读取指定的 Blob 或 File 对象。读取操作完成的时候，readyState 会变成已完成（DONE），并触发 loadend 事件，同时 result 属性将包含一个data:URL格式的字符串（base64编码）以表示所读取文件的内容。

        reader.onload = function(e) {
          self.imgsrc = e.target.result; //图片内容的base64编码
          self.imgSrcArr.push(self.imgsrc)
          self.show = true;
        }
      },
      goAddFault() {
        this.$router.push({
          name: 'deviceFault'
        })
      },
      addPic: function(path) {
        let els = this.$refs.divGenres.querySelectorAll('input[type=file]')
        els[0].click()
        return false

      },

      delImg(i) {
        this.imgSrcArr.splice(i, 1)
      },

    },
    watch: {
      imgSrcArr(newVal) {
        if (newVal.length === 0) {
          this.show = false
          this.showCamera = true
        } else if (newVal.length >= 1) {
          this.showCamera = false
        }
      }
    }
  }
</script>

<style scoped="scoped">
  .van-uploader {
    padding-left: .8rem;
  }

  .list-link {
    display: inline-block;
    width: 5rem;
    margin-right: .9rem;
  }

  progress {
    height: .5rem;
    width: 96%;
    display: flex;
    justify-content: center;
    margin: 0 auto;
    background-color: #e6e6e6;
    color: #0086ff;
    /*IE10*/
    border-radius: 10px;
    margin-top: .9rem;
    -moz-box-shadow: 0px 1px 5px #757575;
    -webkit-box-shadow: 0px 1px 5px #757575;
    box-shadow: 0px 1px 5px #757575;
  }

  progress::-moz-progress-bar {
    background: #0086ff;
  }

  progress::-webkit-progress-bar {
    background: #e6e6e6;
  }

  progress::-webkit-progress-value {
    background: #0086ff;
  }

  /*我用的是上面这几句，下面是网站找到的我也没有试过，有兴趣的可以去试试*/

  /*ie6-ie9*/
  progress ie {
    display: block;
    height: 100%;
    background: #0064B4;
  }

  progress::-moz-progress-bar {
    background: #0064B4;
  }

  progress::-webkit-progress-bar {
    background: #e6e6e6;
  }

  progress::-webkit-progress-value {
    background: #0064B4;
  }

  .van-button--large {
    height: 2.3rem;
    line-height: 2.3rem;
    margin-bottom: .7rem;
  }

  .btn {
    margin-top: .3rem;
    padding: .3rem;
    border-radius: 15px;
  }

  .area {
    overflow: scroll;
  }

  .van-button--default {
    background: whitesmoke;
  }

  .delImg {
    position: relative;
    top: -5.9rem;
    left: 4.5rem;
    border: .4px solid white;
    border-radius: 50%;
    z-index: 99;
    background: white;
    width: 1rem;
    height: 1rem;
  }

  .list-li {
    margin-top: .5rem;
  }

  .van-image {
    object-fit: container;
    height: 5rem;
    width: 5rem;
    margin-right: .4rem;
    border-radius: 6px;
  }

  .isSub {
    padding: .7rem;
    padding-bottom: 0;
  }

  .cremaImg {
    width: 1.5rem;
    height: 1.5rem;
  }

  .imgText {
    margin: 0;
    font-size: .7rem;
    color: #999999;
  }

  .imgslot {
    margin-top: .3rem;
    text-align: center;
    padding: 1rem;
    background: whitesmoke;
    display: inline-block;
  }
</style>
